<?php

namespace App\Classes;
use Illuminate\Support\Facades\DB;
use App\Models\User;
use App\Models\Plan;
use App\Models\Order;
use Filament\Notifications\Notification;

class UpdateStat
{
    public function __construct()
    {
//        $user = User::all();
//
//        foreach($user as $u){
//            $this->autoRenewWithBalance($u->id, $u->plan_id);
//            $this->notifyUserAboutToExpire($u->id);
//            $this->updateUserExpiry($u->id);
//        }

    }

    function autoRenewWithBalance($user_id, $plan_id){
        $user = User::find($user_id);
        $plan = Plan::find($plan_id);
        $balance = $user->balance;
        $amount = $plan->amount;
        if($balance < $amount){
            return;
        }
        $user->update(['balance' => $balance - $amount]);
        $order = Order::create([
            'user_id' => $user_id,
            'plan_id' => $plan_id,
            'status' => 'paid',
            'order_id' => 'auto-renew',
            'payment_id' => 'auto-renew',
            'paid_at' => now(),
        ]);
        updateReferralCommission($plan_id, $order->id, $user->referred_by);
    }

    /**
     * @param $user_id
     * @param $plan_id
     * @return void
     * update user expiry plan periodically
     */
    function updateUserExpiry($user_id)
    {
        $expired_at = User::find($user_id)->expired_at;
        $sent = User::find($user_id)->expiry_notice_sent;

        if(now() > $expired_at && !$sent){
            User::find($user_id)->update(['plan_id' => null, 'expired_at' => null]);
        }

        //send expiry notification to database
        Notification::make('PlanExpired')
            ->title('Your plan has expired')
            ->sendToDatabase(User::find($user_id));
    }

    /**
     * notify user about to expire notification before 3 days
     */
    function notifyUserAboutToExpire($user_id)
    {
        $expired_at = User::find($user_id)->expired_at;
        $three_days_before = date('Y-m-d H:i:s', strtotime($expired_at . ' -3 days'));
        if(now() > $three_days_before){
            Notification::make('PlanAboutToExpire')
                ->title('Your plan is about to expire')
                ->sendToDatabase(User::find($user_id));
        }
    }
}
